package com.dc.web.controller;


import com.dc.constant.MessageConstant;
import com.dc.dao.UserDao;
import com.dc.entity.UserEntity;
import com.dc.model.AjaxResult;
import com.dc.model.LoginBody;
import com.dc.model.RegisterBody;
import com.dc.service.LoginService;
import com.dc.utils.PasswordEncryUtil;
import net.minidev.json.JSONValue;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/api/account")
@RestController
public class LoginController {

    @Resource
    LoginService loginService;

    @Resource
    UserDao userDao;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        String login = loginService.login(loginBody.getUserName(), loginBody.getPassword());
        if (login != null) {
            String passwordCry = PasswordEncryUtil.md5Hex(loginBody.getUserName(), loginBody.getPassword());
            UserEntity user = userDao.findByUserNameAndPassword(loginBody.getUserName(), passwordCry);

            Map<String, Object> map = new HashMap<>();
            map.put("user", user);
            map.put("token", login);
            map.put("menus", JSONValue.parse(user.getMenus()));
            return AjaxResult.success(map);
        } else {
            return AjaxResult.error(MessageConstant.ERR_LOGIN_FAIL);
        }
    }

    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody loginBody) {
        List<UserEntity> allUsers = userDao.findAll();
        if(!ObjectUtils.isEmpty(allUsers)){
            return AjaxResult.error(MessageConstant.ERR_REGISTER_FAIL);     // 如果数据库有数据，不允许注册
        }
        String userName = loginBody.getUserName();
        String password = loginBody.getPassword();
        String name = loginBody.getName();

        boolean b = userDao.existsSysUserByUserName(userName);
        if(b) {
            return AjaxResult.error(MessageConstant.ERR_USER_NAME_IS_EXIST);
        }

        UserEntity user = loginService.register(userName, password, name);

        return AjaxResult.success(user);
    }
}
